import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { Button, Popconfirm, Modal, Form, Input, Radio, InputNumber, Select, App } from 'antd'
import { useModel } from '@umijs/max'
import { PlusOutlined } from '@ant-design/icons'
import './AddServeManage.less'

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 }
}
const { TextArea } = Input
const { Option } = Select

const scopeMap = {
  buy: '买卖套餐',
  rent: '租赁套餐'
}
const scopeSelection = [
  {
    label: '买卖套餐',
    value: 'buy'
  },
  {
    label: '租赁套餐',
    value: 'rent'
  }
]

export default () => {
  const { GetGoodsGainList, AddGoodsGain, EditGoodsGain, SetGoodsGainStatus, NewGetGoodsGainTypeMap } =
    useModel('AddServeManage')

  const { message } = App.useApp()

  const tableRef = useRef()
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量

  const [addAndEditModalVisible, setAddAndEditModalVisible] = useState(false) // 新增/编辑增值服务弹窗
  const [addAndEditModalType, setAddAndEditModalType] = useState('add') // 新增/编辑增值服务弹窗类型

  const [formRef] = Form.useForm()
  const [modelSelectList, setModelSelectList] = useState([]) // 下拉框数据
  const [editId, setEditId] = useState('') // 编辑id

  // 获取下拉框数据
  const getModelSelectList = async () => {
    const res = await NewGetGoodsGainTypeMap()
    if (res) {
      let arr = []
      for (const resKey in res) {
        arr.push({
          label: res[resKey].split('/')[0],
          value: Number(resKey),
          subLabel: res[resKey].split('/')[1]
        })
      }
      setModelSelectList(arr)
      formRef.setFieldsValue({
        type: arr[0].value
      })
    }
  }

  // 失效 / 生效
  const handleFailureAndTakeEffect = async id => {
    const res = await SetGoodsGainStatus({ id })
    if (res) {
      message.success('操作成功')
      tableRef.current.reload()
    }
  }

  // 新增/编辑增值服务
  const handleAddAndEdit = async (type, row) => {
    await getModelSelectList()
    formRef.setFieldsValue({
      status: 1,
      use_scope: 'rent'
    })
    setAddAndEditModalType(type)
    setAddAndEditModalVisible(true)

    if (type === 'edit') {
      setEditId(row.id)
      formRef.setFieldsValue({
        ...row
      })
    }
  }

  // 关闭弹窗
  const handleAddAndEditCancel = () => {
    setAddAndEditModalVisible(false)
    formRef.resetFields()
  }

  // 新增/编辑增值服务弹窗确认
  const handleAddAndEditOk = async () => {
    let type = addAndEditModalType
    let res
    if (type === 'add') {
      res = await AddGoodsGain(formRef.getFieldsValue())
    } else if (type === 'edit') {
      let params = {
        id: editId,
        ...formRef.getFieldsValue()
      }
      res = await EditGoodsGain(params)
    }
    if (res) {
      message.success('操作成功')
      handleAddAndEditCancel()
      tableRef.current.reload()
    }
  }

  useEffect(() => {}, [])

  const columns = [
    {
      title: '服务编码',
      dataIndex: 'id',
      width: 80,
      align: 'center'
    },
    {
      title: '服务名称',
      dataIndex: 'name',
      width: 100,
      align: 'center'
    },
    {
      title: '适用范围',
      dataIndex: 'use_scope',
      width: 100,
      align: 'center',
      hideInSearch: true,
      render: text => scopeMap[text]
    },
    {
      title: '类型',
      dataIndex: 'type_name',
      width: 100,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 80,
      align: 'center',
      hideInSearch: true,
      render: (text, record) => {
        return (
          <>
            {record.type === 3 && <div>{text}%</div>}
            {record.type === 2 && <div>-</div>}
            {record.type === 1 && <div>{text}元</div>}
          </>
        )
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      align: 'center',
      valueEnum: {
        1: {
          text: '生效中',
          status: 'Success'
        },
        2: {
          text: '已失效',
          status: 'Error'
        }
      },
      valueType: 'select'
    },
    {
      title: '所属类目',
      dataIndex: 'industry',
      width: 80,
      hideInSearch: true,
      align: 'center'
    },
    {
      title: '服务描述',
      dataIndex: 'remark',
      width: 150,
      hideInSearch: true,
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 150,
      hideInSearch: true,
      align: 'center'
    },
    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        let { status } = row
        return (
          <>
            {
              <>
                <Button type='link' key='edit' onClick={() => handleAddAndEdit('edit', row)}>
                  编辑
                </Button>
                {status === 1 ? (
                  <Popconfirm
                    key='failure'
                    title='是否确定将该增值服务失效（失效后之前已经使用过的服务不受影响）'
                    onConfirm={() => handleFailureAndTakeEffect(row.id)}
                    okText='确认'
                    cancelText='取消'
                  >
                    <Button type='link' danger>
                      失效
                    </Button>
                  </Popconfirm>
                ) : (
                  <Button type='link' key='take_effect' onClick={() => handleFailureAndTakeEffect(row.id)}>
                    生效
                  </Button>
                )}
              </>
            }
          </>
        )
      }
    }
  ]

  return (
    <>
      <ProTable
        actionRef={tableRef}
        request={async params => {
          const filters = {
            name: params.name,
            id: params.id,
            status: params.status
          }

          const param = {
            page: params.current,
            page_size: params.pageSize,
            ...filters
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          const res = await GetGoodsGainList(param)

          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey='id'
        scroll={{ x: 'max-content' }}
        columns={columns}
        headerTitle={
          <Button
            icon={<PlusOutlined />}
            key={Math.random().toString()}
            type='primary'
            onClick={() => handleAddAndEdit('add')}
          >
            新建增值服务
          </Button>
        }
        search={{
          defaultCollapsed: false,
          labelWidth: 80,
          span: 6
        }}
      />

      {/* 新增/编辑弹窗 */}
      <Modal
        title={addAndEditModalType === 'add' ? '新增增值服务' : '编辑增值服务'}
        mask
        open={addAndEditModalVisible}
        onCancel={() => handleAddAndEditCancel()}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        onOk={() => formRef.submit()}
      >
        <Form form={formRef} onFinish={handleAddAndEditOk} name='form_modal' {...formItemLayout}>
          <Form.Item name='name' label='服务名称 : ' rules={[{ required: true, message: '请输入服务名称' }]}>
            <Input placeholder='请输入' allowClear />
          </Form.Item>
          <Form.Item name='use_scope' label='适用范围 : ' rules={[{ required: true, message: '请输入适用范围' }]}>
            <Select placeholder='请选择' options={scopeSelection}></Select>
          </Form.Item>
          <Form.Item name='type' label='类型 : ' rules={[{ required: true, message: '请选择类型' }]}>
            <Select style={{ width: '100%' }} optionLabelProp='label'>
              {modelSelectList.map((item, index) => {
                return (
                  <Option value={item.value} label={item.label} key={item.label}>
                    <div className='select_list'>
                      <span>{item.label}</span>
                      <span>{item.subLabel}</span>
                    </div>
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item
            name='price'
            label='价格 : '
            rules={[{ required: true, message: '请输入价格' }]}
            help='用户选择增值服务需要支付的价格'
          >
            <InputNumber placeholder='请输入' addonAfter='元' style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name='remark' label='内容描述 : ' rules={[{ required: true, message: '请输入内容描述' }]}>
            <TextArea showCount maxLength={200} placeholder='请输入' allowClear />
          </Form.Item>
          <Form.Item name='status' label='状态 : ' rules={[{ required: true, message: '请选择状态' }]}>
            <Radio.Group>
              <Radio value={1}>生效</Radio>
              <Radio value={2}>失效</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
